package com.example.myui.activity.service;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.example.myui.activity.BindServiceActivity;

/**
 * Created by Administrator on 2018/3/14/014.
 */

public class MyIntentService1 extends IntentService {

    private static final String TAG = MyIntentService1.class.getSimpleName();
    private LocalBroadcastManager instance;

    public MyIntentService1() {
        super("MyIntentService1");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        instance = LocalBroadcastManager.getInstance(this);
        sendServiceStatus("服务启动" + Thread.currentThread().getName());
    }


    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

        Log.i(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        sendServiceStatus("服务结束" + Thread.currentThread().getName());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: " + intent.getStringExtra("str"));
        //做耗时操作 发送线程消息
        sendThreadStatus("线程启动");
        try {
            int count = 0;
            boolean inRunning = true;
            while (inRunning) {
                count++;
                sendThreadStatus("线程进度 ：" + count + Thread.currentThread().getName());
                if (count == 4) {
                    inRunning = false;
                }
                Thread.sleep(1000);
            }

            sendThreadStatus("线程结束");
//            stopSelf();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //发送服务消息
    private void sendServiceStatus(String status) {
        Intent intent = new Intent(BindServiceActivity.ACTION_TYPE_SERVICE);
        intent.putExtra("service", status);
        instance.sendBroadcast(intent);
    }


    //发送线程消息
    private void sendThreadStatus(String status) {
        Intent intent = new Intent(BindServiceActivity.ACTION_TYPE_THREAD);
        intent.putExtra("thread", status);
        instance.sendBroadcast(intent);
    }
}
